

import jwt
import requests

from api.mylogger import logger
import littleshinserver.settings


def wechat_openid_by_wechat_code(code):
    appid = littleshinserver.settings.WECHAT_APPID
    secret = littleshinserver.settings.WECHAT_APPSECRET
    url = 'https://api.weixin.qq.com/sns/oauth2/access_token'
    headers = {
        'Content-Type': 'application/json'
    }
    code_data = {
        'appid': appid,
        'secret': secret,
        'code': code,
        'grant_type': 'authorization_code',
    }
    # print(params)
    token_rsp = requests.get(url, params=code_data, headers=headers)
    token_rsp.encoding = 'utf-8'
    res = token_rsp.json()
    openid = res.get('openid', '')
    access_token = res.get('access_token', '')
    return openid, access_token


def wechat_userinfo(openid, access_token):
    url = 'https://api.weixin.qq.com/sns/userinfo'
    headers = {
        'Content-Type': 'application/json'
    }
    token_data = {
        'access_token': access_token,
        'openid': openid,
    }
    user_res = requests.get(url, params=token_data, headers=headers)
    user_res.encoding = 'utf-8'
    res = user_res.json()
    return res

